/**
 * 时间戳
 * @param {*} timestamp  时间戳
 */
const timestampToTime = timestamp => {
  let date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  let Y = date.getFullYear() + "-";
  let M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  let D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
  let h =
    (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  let m =
    (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
    ":";
  let s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return Y + M + D + h + m + s;
};
/**
 * 存储localStorage
 */
const setStore = (name, content) => {
  if (!name) return;
  if (typeof content !== "string") {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
};

/**
 * 获取localStorage
 */
const getStore = name => {
  if (!name) return;
  return window.localStorage.getItem(name);
};

/**
 * 删除localStorage
 */
const removeStore = name => {
  if (!name) return;
  window.localStorage.removeItem(name);
};

/**
 * 设置cookie
 **/
function setCookie(name, value, day) {
  let date = new Date();
  date.setDate(date.getDate() + day);
  document.cookie = name + "=" + value + ";expires=" + date;
}

/**
 * 获取cookie
 **/
function getCookie(name) {
  let reg = RegExp(name + "=([^;]+)");
  let arr = document.cookie.match(reg);
  if (arr) {
    return arr[1];
  } else {
    return "";
  }
}

/**
 * 删除cookie
 **/
function delCookie(name) {
  setCookie(name, null, -1);
}

// 格式化日对象
const getNowDate = date => {
  // var date = new Date();
  var sign2 = ":";
  var year = date.getFullYear(); // 年
  var month = date.getMonth() + 1; // 月
  var day = date.getDate(); // 日
  var hour = date.getHours(); // 时
  var minutes = date.getMinutes(); // 分
  var seconds = date.getSeconds(); //秒
  var weekArr = [
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
    "星期天"
  ];
  var week = weekArr[date.getDay()];
  // 给一位数的数据前面加 “0”
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  if (hour >= 0 && hour <= 9) {
    hour = "0" + hour;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = "0" + minutes;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = "0" + seconds;
  }
  return (
    year +
    "年" +
    month +
    "月" +
    day +
    "日 " +
    hour +
    sign2 +
    minutes +
    sign2 +
    seconds +
    " " +
    week
  );
};

//转base64
function toBase64(imgUrl) {
  //imgUrl 图片地址
  // 一定要设置为let，不然图片不显示
  let image = new Image();
  // 解决跨域问题
  image.setAttribute("crossOrigin", "anonymous");
  const imageUrl = imgUrl;
  image.src = imageUrl;
  // image.onload为异步加载
  image.onload = () => {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    var context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    var quality = 0.8;
    // 这里的dataurl就是base64类型
    // 使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
    const dataurl = canvas.toDataURL("image/jpeg", quality);
    console.log("dataurl", dataurl);
    return dataurl;
  };
}

// 时间显示多少分钟前
function friendlyFormatTime(stringTime) {
  let str = stringTime;
  //将字符串转换成时间格式 console.log(this.friendlyFormatTime('2021-12-22 17:42:09'));
  let timePublish = new Date(str);
  let timeNow = new Date();
  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  let month = day * 30;
  let year = month * 12;
  let diffValue = timeNow - timePublish;
  let diffMonth = diffValue / month;
  let diffWeek = diffValue / (7 * day);
  let diffDay = diffValue / day;
  let diffHour = diffValue / hour;
  let diffMinute = diffValue / minute;
  let diffYear = diffValue / year;
  let result = null;
  if (diffValue < 0) {
    result = "刚刚";
  } else if (diffYear > 1) {
    result = parseInt(diffYear) + "年前";
  } else if (diffMonth > 1) {
    result = parseInt(diffMonth) + "月前";
  } else if (diffWeek > 1) {
    result = parseInt(diffWeek) + "周前";
  } else if (diffDay > 1) {
    result = parseInt(diffDay) + "天前";
  } else if (diffHour > 1) {
    result = parseInt(diffHour) + "小时前";
  } else if (diffMinute > 1) {
    result = parseInt(diffMinute) + "分钟前";
  } else {
    result = "刚刚";
  }
  return result;
}

// 时间判断今天 昨天 几天前
function judgeTime(date) {
  let dateStr = new Date(date.replace(/-/g, "/"));
  let today = new Date();
  today.setHours(0);
  today.setMinutes(0);
  today.setSeconds(0);
  today.setMilliseconds(0);
  let otime = today.getTime();
  // 给出时间 - 今天0点
  let offset = dateStr.getTime() - otime;
  let isToday = offset / 1000 / 60 / 60;
  if (isToday > 0 && isToday <= 24) {
    return "今天";
  } else if (isToday < 0 && isToday >= -24) {
    return "昨天";
  } else {
    return date.substring(0, 10); //只留年月日
  }
}

// 随机生成字符串
function getRandomString(len) {
  let _charStr =
      "abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789",
    min = 0,
    max = _charStr.length - 1,
    _str = ""; //定义随机字符串 变量
  //判断是否指定长度，否则默认长度为15
  len = len || 15;
  //循环生成字符串
  for (var i = 0, index; i < len; i++) {
    index = (function(randomIndexFunc, i) {
      return randomIndexFunc(min, max, i, randomIndexFunc);
    })(function(min, max, i, _self) {
      let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
        numStart = _charStr.length - 10;
      if (i == 0 && indexTemp >= numStart) {
        indexTemp = _self(min, max, i, _self);
      }
      return indexTemp;
    }, i);
    _str += _charStr[index];
  }
  return _str;
}

// 全局配置，生产环境取消 console.log 的控制台输出
function consoleCancle(sign) {
  console.log = (function(oriLogFunc) {
    return function() {
      if (sign) {
        oriLogFunc.apply(this, arguments);
      }
    };
  })(console.log);
}

/**
 * 导出
 **/
export {
  timestampToTime,
  setStore,
  getStore,
  removeStore,
  setCookie,
  getCookie,
  delCookie,
  getNowDate,
  toBase64,
  friendlyFormatTime,
  judgeTime,
  getRandomString,
  consoleCancle
};
